package com.jbxie.spaceiotmqtt.mqttUtils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 发布消息的回调类
 *
 * 必须实现MqttCallback的接口并实现对应的相关接口方法CallBack 类将实现 MqttCallBack。
 * 每个客户机标识都需要一个回调实例。在此示例中，构造函数传递客户机标识以另存为实例数据。
 * 在回调中，将它用来标识已经启动了该回调的哪个实例。
 * 必须在回调类中实现三个方法：
 *
 *  public void messageArrived(MqttTopic topic, MqttMessage message)接收已经预订的发布。
 *
 *  public void connectionLost(Throwable cause)在断开连接时调用。
 *
 *  public void deliveryComplete(MqttDeliveryToken token))
 *  接收到已经发布的 QoS 1 或 QoS 2 消息的传递令牌时调用。
 *  由 MqttClient.connect 激活此回调。
 *
 */

@Slf4j
@Component
public class MqttClientCallback implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(MqttClientCallback.class);

    @Override
    public void connectionLost(Throwable arg0) {
        //logger.info("连接断开，可以做重连");
        System.out.println("mqtt失去了连接");
        MyMqttClient.reConnect();
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        //logger.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
        System.out.println("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
//        logger.info("接收消息主题 : " + topic);
//        logger.info("接收消息Qos : " + mqttMessage.getQos());
//        logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));
        String messages = new String(mqttMessage.getPayload());
        if(!messages.equals("close")){
            System.out.println("{");
            System.out.println("接收消息主题 : " + topic);
            System.out.println("接收消息Qos : " + mqttMessage.getQos());
            System.out.println("接收消息内容 : " + messages);
            System.out.println("}");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            logger.info("接收时间========" + df.format(new Date()) + " " + System.currentTimeMillis());
//            try {
//                perform(topic,json);
//            }catch (Exception e){
//            }
        }
//        if (MyMqttClient.executorService != null) {
//            MyMqttClient.executorService.execute(new HandlerThread(topic, content));
//        }
    }

    public  void perform(String topicP, JSONObject json) throws MqttException, UnsupportedEncodingException {
        //你的业务模块
    }
}
